import { defineStore } from "pinia";
import { ref } from 'vue';
import { io } from 'socket.io-client'

export const useWsStore = defineStore('wsStore', () => {
    const socket = ref(null);
    const data = ref(null);
    const initSocket = () => {
        socket.value = io('http://localhost:5000', {
            transports: ['websocket','polling'],
            reconnection: true,
            reconnectionAttempts: Infinity,
            reconnectionDelay: 1000
        });
        socket.value.on('connect', () => {
            console.log("Socket.IO connected");
        });
        socket.value.on('disconnect', () => {
            console.log("Socket.IO disconnected");
        });
        // 接收后端发来的数据
        socket.value.on('alert_update1', (payload) => {
            try {
                const parsed = typeof payload === 'string' ? JSON.parse(payload) : payload;
                console.log('Parsed payload:', parsed);
                if (parsed?.code === 200) {
                    data.value = parsed;
                    console.log(data.value);
                    // return data.value
                } else {
                    console.error('无效的数据格式', parsed);
                }
            } catch (e) {
                console.error('JSON 解析失败', e);
            }
        });
        // socket.value.on('alert_update2',(payload) => {
        //     if (payload.code === 200) {
        //         data.value = payload.data;
        //     } else {
        //         console.error("请求失败，错误代码：",payload.code);
                
        //     }
        // })
    };
    const sendMessage = (message) => {
        if (socket.value?.connected) {
            socket.value.emit('page',{ page: message });
        } else {
            console.warn("Socket.IO尚未连接，消息已忽略");
        }
    };
    return { socket, data, initSocket, sendMessage };
})